package com.gjy.util.sb.advice;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Objects;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-10-23 14:55:13
 */
@RestControllerAdvice
public class RequestBodyAdviceImpl implements RequestBodyAdvice {

    private static final Logger log = LoggerFactory.getLogger(RequestBodyAdviceImpl.class);

    @Override
    public boolean supports(MethodParameter parameter, Type type, Class<? extends HttpMessageConverter<?>> cls) {
        return true;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage message, MethodParameter parameter, Type type, Class<? extends HttpMessageConverter<?>> cls) throws IOException {
        RequestMapping mapping = parameter.getMethodAnnotation(RequestMapping.class);
        if (Objects.nonNull(mapping)) {
            log.info("url: {}", Arrays.toString(mapping.path()));
        }
        log.info("请求入口: {}", parameter.getExecutable());
        return message;
    }

    @Override
    public Object afterBodyRead(Object o, HttpInputMessage message, MethodParameter parameter, Type type, Class<? extends HttpMessageConverter<?>> cls) {
        log.info("请求参数: {}", o);
        return o;
    }

    @Override
    public Object handleEmptyBody(Object o, HttpInputMessage message, MethodParameter parameter, Type type, Class<? extends HttpMessageConverter<?>> cls) {
        log.info("请求体为空: {}", o);
        return o;
    }
}
